package com.louis.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.FileCopyUtils;

import java.io.*;


/**
 * @author Lijun jiang
 * @Date: Jun 7, 2011
 * @Time: 2:37:38 PM
 */

public abstract class DocumentUtil {
    private static final Log logger = LogFactory.getLog(DocumentUtil.class);
    public static String BASE_DIR = "";

    static {
        try {
            BASE_DIR = PropertiesLoaderUtils.loadAllProperties("application.properties").getProperty("document.upload.dir");
        } catch (IOException e) {
            BASE_DIR = "target";
        }
    }

    public static boolean upload(String category, String fileName, byte[] bytes) {
        File guidDirectory = new File(BASE_DIR, category);
        File document = new File(guidDirectory, fileName);
        guidDirectory.mkdirs();
        OutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(document.getAbsolutePath()));
            out.write(bytes);
        } catch (IOException e) {
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return true;
    }

    public static InputStream download(String category, String fileName) {
        File directory = new File(BASE_DIR, category);
        File document = new File(directory, fileName);
        try {
            return new FileInputStream(document);
        } catch (FileNotFoundException e) {
            logger.error(document + " can not be found!");
            return null;
        }
    }

    public static byte[] downloadAsBytes(String category, String fileName) {
        File file = downloadAsFile(category, fileName);
        try {
            return FileCopyUtils.copyToByteArray(file);
        } catch (IOException e) {
            logger.error("Error downloading file " + fileName, e);
            return null;
        }
    }

    public static void delete(String category, String fileName) {
        try {
            File directory = new File(BASE_DIR, category);
            File document = new File(directory, fileName);
            document.delete();
            directory.delete();
        } catch (Exception e) {
            logger.error(e);
        }

    }

    public static File downloadAsFile(String category, String fileName) {
        File directory = new File(BASE_DIR, category);
        return new File(directory, fileName);
    }

    public static boolean existFile(String category, String compressedFileName) {
        File directory = new File(BASE_DIR, category);
        File document = new File(directory, compressedFileName);
        return document.exists();
    }
}